package com.dingtalk.chatbot;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.crawler.common.WebhookConstant;
import com.dingtalk.chatbot.message.Message;

/**
 * Created by dustin on 2017/3/17.
 */
public class DingtalkChatbotClient {

    HttpClient httpclient = HttpClients.createDefault();
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    /**
     * 钉钉推送
     * @param webhook
     * @param message
     * @return
     * @throws IOException
     */
    public SendResult send(String webhook, Message message) throws IOException{

        HttpPost httppost = new HttpPost(webhook);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
        httppost.setEntity(se);

        SendResult sendResult = new SendResult();
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            try {
            	JSONObject obj = JSONObject.parseObject(result);
            	Integer errcode = obj.getInteger("errcode");
            	sendResult.setErrorCode(errcode);
            	sendResult.setErrorMsg(obj.getString("errmsg"));
            	sendResult.setIsSuccess(errcode.equals(0));            	
            }
            catch (Exception e) {
            	logger.error("响应内容处理失败：{} \n{} ", result, e.getMessage());
			}
            
        }

        return sendResult;
    }
    
   
    /**
     * 简易推送
     * @param webhook
     * @param body
     */
    public static void simpleSend(String webhook, JSONObject body) {
    	try{
    		HttpClient httpclient = HttpClients.createDefault();
        	HttpPost httppost = new HttpPost(webhook);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");
            StringEntity se = new StringEntity(body.toJSONString(), "utf-8");
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            	//TODO
            }
    	}
    	catch( IOException ex){
    		// 不做处理
    	}
    	
    }
    
    /**
     * 简易推送
     * @param body
     */
    public static void simpleSend(JSONObject body){
    	simpleSend(WebhookConstant.WEBHOOK, body);
    }

}


